/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * frmSearch.java
 *
 * Created on 11-03-2011, 13:04:47
 */

package GUI;

import interact.DataInteraction;
import interact.ValidateData;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JCheckBox;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author UnderGround
 */
public class frmSearch extends javax.swing.JPanel implements TableModelListener{
    DefaultTableModel dtm;
    /** Creates new form frmSearch */
    public frmSearch() {
         vtgetBookChoice = new Vector();
        initComponents();
       loadDataToTable();
        totalRecord =  DataInteraction.countBooksRecord();
        tblSearch.getModel().addTableModelListener(this);
         loadTable();
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(frmSearch.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            Logger.getLogger(frmSearch.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(frmSearch.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedLookAndFeelException ex) {
            Logger.getLogger(frmSearch.class.getName()).log(Level.SEVERE, null, ex);
        }
        System.out.println(vtgetBookChoice);
    }
    public void loadDataToTable(){
        dtm = DataInteraction.loadDataTableWhenSearch(tblSearch, start, condition,keyword);
    }
    public static void loadTable(){
           vtgetBookChoice = new Vector();
        count.setText(String.valueOf(totalRecord));
//        DataInteraction.loadDataTableWhenSearch(tblSearch, start, condition,keyword);
        System.out.println("loaded");
        totalRecord =  DataInteraction.countBooksRecord();
        if(totalRecord>numberRecord){
            btnLast.setEnabled(true);
        }
        if(totalRecord ==0 || totalRecord< numberRecord){
            btnFirst.setEnabled(false);
            btnPreview.setEnabled(false);
            btnLast.setEnabled(false);
            btnNext.setEnabled(false);
        }
        else{
            btnLast.setEnabled(true);
            btnNext.setEnabled(true);
        }

         tblSearch.getColumnModel().getColumn(0).setPreferredWidth(30);
         tblSearch.getColumnModel().getColumn(1).setPreferredWidth(120);
         tblSearch.getColumnModel().getColumn(2).setPreferredWidth(120);
         tblSearch.getColumnModel().getColumn(3).setPreferredWidth(120);
         tblSearch.getColumnModel().getColumn(4).setPreferredWidth(120);
         tblSearch.getColumnModel().getColumn(5).setPreferredWidth(40);
         tblSearch.getColumnModel().getColumn(6).setPreferredWidth(30);
         DataInteraction.loadDataTableWhenSearch(tblSearch, start, condition,keyword);
    }
     

    public void Search(){
        keyword = txtKeyword.getText().trim();

        SearchModel = (String) cbxSearchModel.getSelectedItem();
        //set search model by ISBN
        if (SearchModel.trim().equals("ISBN")) {
            condition = 1;
        }
        //set search model by Author name
        else if (SearchModel.trim().equals("Author name")) {
            condition = 2;
        }
        //set search model by Title
        else if (SearchModel.trim().equals("Title of book")) {
            condition = 3;
        }
        //set search all
        else if (SearchModel.trim().equals("All")) {
            condition = 4;
        }
//        tblSearch.getModel().removeTableModelListener(this);
        
        DataInteraction.loadDataTableWhenSearch(tblSearch, start, condition, keyword);
         tblSearch.getColumnModel().getColumn(0).setPreferredWidth(30);
         tblSearch.getColumnModel().getColumn(1).setPreferredWidth(120);
         tblSearch.getColumnModel().getColumn(2).setPreferredWidth(120);
         tblSearch.getColumnModel().getColumn(3).setPreferredWidth(120);
         tblSearch.getColumnModel().getColumn(4).setPreferredWidth(120);
         tblSearch.getColumnModel().getColumn(5).setPreferredWidth(40);
         tblSearch.getColumnModel().getColumn(6).setPreferredWidth(30);

//        tblSearch.getModel().addTableModelListener(this);
    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        btnPreview = new javax.swing.JButton();
        btnLast = new javax.swing.JButton();
        btnNext = new javax.swing.JButton();
        btnFirst = new javax.swing.JButton();
        count = new javax.swing.JTextField();
        txtKeyword = new javax.swing.JTextField();
        btnSeach = new javax.swing.JButton();
        cbxSearchModel = new javax.swing.JComboBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblSearch = new javax.swing.JTable(){
            public boolean isCellEditable(int row, int column) {
                if (column == 6) {
                    return true;
                } else
                return false;
            }
        };
        btnCheckIn = new javax.swing.JButton();
        btnCheckOut = new javax.swing.JButton();

        setBackground(new java.awt.Color(153, 153, 153));
        setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jPanel1.setBackground(new java.awt.Color(102, 102, 102));
        jPanel1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        btnPreview.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Previous.png"))); // NOI18N
        btnPreview.setText("Preview");
        btnPreview.setEnabled(false);
        btnPreview.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnPreviewActionPerformed(evt);
            }
        });

        btnLast.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/end.png"))); // NOI18N
        btnLast.setText(">>Last");
        btnLast.setEnabled(false);
        btnLast.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLastActionPerformed(evt);
            }
        });

        btnNext.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Next.png"))); // NOI18N
        btnNext.setText(" Next");
        btnNext.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNextActionPerformed(evt);
            }
        });

        btnFirst.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/first.png"))); // NOI18N
        btnFirst.setText("First");
        btnFirst.setEnabled(false);
        btnFirst.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnFirstActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(244, Short.MAX_VALUE)
                .addComponent(btnFirst)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnPreview)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(count, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnNext)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnLast)
                .addGap(19, 19, 19))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnLast)
                    .addComponent(btnNext)
                    .addComponent(count, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnPreview)
                    .addComponent(btnFirst))
                .addContainerGap(50, Short.MAX_VALUE))
        );

        add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(1, 418, 710, 90));

        txtKeyword.setText("Enter key word ........");
        txtKeyword.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                txtKeywordMouseClicked(evt);
            }
        });
        txtKeyword.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtKeywordKeyReleased(evt);
            }
        });
        add(txtKeyword, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 20, 150, 20));

        btnSeach.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/search1.png"))); // NOI18N
        btnSeach.setText("Seach");
        btnSeach.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSeachActionPerformed(evt);
            }
        });
        add(btnSeach, new org.netbeans.lib.awtextra.AbsoluteConstraints(310, 20, -1, -1));

        cbxSearchModel.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "                All", "              ISBN", "         Author name", "         Title of book" }));
        add(cbxSearchModel, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 20, -1, -1));

        tblSearch.setBackground(new java.awt.Color(255, 255, 204));
        tblSearch.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
        tblSearch.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tblSearch.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(tblSearch);

        add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 69, 710, 350));

        btnCheckIn.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/check_in.png"))); // NOI18N
        btnCheckIn.setText("Check in");
        btnCheckIn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCheckInActionPerformed(evt);
            }
        });
        add(btnCheckIn, new org.netbeans.lib.awtextra.AbsoluteConstraints(570, 20, 100, -1));

        btnCheckOut.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/checkout.png"))); // NOI18N
        btnCheckOut.setText("Check out");
        btnCheckOut.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCheckOutActionPerformed(evt);
            }
        });
        add(btnCheckOut, new org.netbeans.lib.awtextra.AbsoluteConstraints(450, 20, 100, -1));
    }// </editor-fold>//GEN-END:initComponents

    private void txtKeywordKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtKeywordKeyReleased
        Search();
}//GEN-LAST:event_txtKeywordKeyReleased

    private void btnSeachActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSeachActionPerformed
        Search();
}//GEN-LAST:event_btnSeachActionPerformed

    private void txtKeywordMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtKeywordMouseClicked
         keyword = txtKeyword.getText().trim();
        if(keyword.equals("Enter key word ........")){
            txtKeyword.setText(null);
        }else{
         txtKeyword.setText(keyword);
         }
    }//GEN-LAST:event_txtKeywordMouseClicked

    private void btnCheckOutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCheckOutActionPerformed
        if (vtgetBookChoice.size() <= 0) {
            ValidateData.showMessage("please select book(s) to borrow");
        } else {
            frmcheckOut checkOut = new frmcheckOut(this, true, vtgetBookChoice);
            checkOut.setParentForm(this);
            checkOut.setModal(true);
            checkOut.setVisible(true);
        }
    }//GEN-LAST:event_btnCheckOutActionPerformed

    private void btnCheckInActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCheckInActionPerformed
//        rowSelected = tblSearch.getSelectedRow();
//        if (rowSelected == -1) {
//            ValidateData.showMessage("please choose a book");
//            return;
//        }
//        if (!DataInteraction.check_Borrower(Integer.parseInt(id))) {
//            ValidateData.showMessage("this book no one has borrowed");
//        }
//        else {
//            String id = tblSearch.getValueAt(rowSelected, 0).toString();
        
            frmCheckIn checkIn = new frmCheckIn(this, true);
            checkIn.setModal(true);
            checkIn.setVisible(true);
//        }
         
    }//GEN-LAST:event_btnCheckInActionPerformed

    private void btnFirstActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFirstActionPerformed
        tblSearch.getModel().removeTableModelListener(this);
        start = 0;
        DataInteraction.loadDataTableWhenSearch(tblSearch, start, condition, keyword);
        btnFirst.setEnabled(false);
        btnPreview.setEnabled(false);
        loadTable();
          tblSearch.getModel().addTableModelListener(this);
}//GEN-LAST:event_btnFirstActionPerformed

    private void btnNextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNextActionPerformed
         tblSearch.getModel().removeTableModelListener(this);
        
        start += numberRecord;
        //        DataInteraction.loadDataTableWhenSearch(tblSearch, start, condition, keyword);
        loadTable();
        if (tblSearch.getModel().getRowCount() < numberRecord) {
            btnNext.setEnabled(false);
            btnLast.setEnabled(false);
        }
        btnFirst.setEnabled(true);
        btnPreview.setEnabled(true);
        tblSearch.getModel().addTableModelListener(this);
}//GEN-LAST:event_btnNextActionPerformed

    private void btnLastActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLastActionPerformed
        tblSearch.getModel().removeTableModelListener(this);
        start = numberRecord*(totalRecord/numberRecord);
        //        DataInteraction.loadDataTableWhenSearch(tblSearch, start, condition, keyword);
        loadTable();
        btnFirst.setEnabled(true);
        btnPreview.setEnabled(true);
        btnLast.setEnabled(false);
        btnNext.setEnabled(false);
          tblSearch.getModel().addTableModelListener(this);
    }//GEN-LAST:event_btnLastActionPerformed

    private void btnPreviewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPreviewActionPerformed
        // TODO add your handling code here:
         tblSearch.getModel().removeTableModelListener(this);
        start -=numberRecord;
        //        DataInteraction.loadDataTableWhenSearch(tblSearch, start, condition, keyword);
        loadTable();
        btnNext.setEnabled(true);
        btnLast.setEnabled(true);
        if(start ==0){
            btnPreview.setEnabled(false);
            btnFirst.setEnabled(false);
        }
        if(tblSearch.getRowCount()>0){
            btnNext.setEnabled(true);
            btnLast.setEnabled(true);
        }
          tblSearch.getModel().addTableModelListener(this);
}//GEN-LAST:event_btnPreviewActionPerformed
    private static int totalRecord;
    public static Vector vtgetBookChoice;
    private static String keyword,SearchModel;
    private static int condition =0;
    private static int start =0;
    private static int numberRecord =20;
    private int rowSelected;
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private static javax.swing.JButton btnCheckIn;
    private static javax.swing.JButton btnCheckOut;
    private static javax.swing.JButton btnFirst;
    private static javax.swing.JButton btnLast;
    private static javax.swing.JButton btnNext;
    private static javax.swing.JButton btnPreview;
    private static javax.swing.JButton btnSeach;
    private javax.swing.JComboBox cbxSearchModel;
    private static javax.swing.JTextField count;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    public static javax.swing.JTable tblSearch;
    private javax.swing.JTextField txtKeyword;
    // End of variables declaration//GEN-END:variables

    public  void tableChanged(TableModelEvent e) {
        try{
                rowSelected = tblSearch.getSelectedRow();
               System.out.println(rowSelected);
                if(rowSelected != -1){
                      Object value = tblSearch.getValueAt(rowSelected,6);
                       Boolean b = Boolean.valueOf(value.toString());
                        if (b == true) {
                           String quantity =tblSearch.getValueAt(rowSelected, 5).toString();
                            System.out.println(quantity);
                          if(!ValidateData.checkQuantity(quantity)){
                            ValidateData.showMessage("This books in the library is not available");
                            return;
                          }else{
                          vtgetBookChoice.add(tblSearch.getValueAt(rowSelected, 1));
                          }
                } else if (b == false) {
                    vtgetBookChoice.removeElement(tblSearch.getValueAt(rowSelected, 1));
                }
                }
                
                System.out.println("vt  "+vtgetBookChoice.toString());
        }
        catch(java.lang.ArrayIndexOutOfBoundsException ex){
        
        }
    }
}




